import {
  getIceServers,
  handleCall,
  createOffer,
  setAnswer,
  handleCloseCall,
  addIceCandidate,
  getIceCandidate,
} from '../services/webrtc-services.js'

// Handle get the ICE server configuration
export const handleGetIceServersRequest = async (socket) => {
  try {
    const data = await getIceServers()
    data.iceServers[0].urls = data.iceServers[0].urls[0]
    console.log('Get the ICE server configuration')
    socket.emit('getIceServersResponse', data)
  } catch (error) {
    console.error('Error getting ICE server configuration:', error)
  }
}
// Handle call
export const handleCallRequest = async (socket, url, offer) => {
  try {
    const data = await handleCall(url, offer)
    console.log('Send offer and get answer')
    socket.emit('callResponse', data)
  } catch (error) {
    console.error('Error sending offer and getting answer:', error)
  }
}

// Handle create offer
export const handleCreateOfferRequest = async (socket, url) => {
  try {
    const data = await createOffer(url)
    console.log('Create an offer')
    socket.emit('createOfferResponse', data)
  } catch (error) {
    console.error('Error creating offer:', error)
  }
}

// Handle set answer
export const handleSetAnswerRequest = async (socket, url, answer) => {
  try {
    const data = await setAnswer(url, answer)
    console.log('Set an answer')
    socket.emit('setAnswerResponse', data)
  } catch (error) {
    console.error('Error setting answer:', error)
  }
}

// Handle close the call
export const handleHangupRequest = async (socket, url) => {
  try {
    const data = await handleCloseCall(url)
    console.log('Close the call')
    socket.emit('hangupResponse', data)
  } catch (error) {
    console.error('Error closing call:', error)
  }
}

// Handle add ICE candidates
export const handleAddIceCandidateRequest = async (socket, url, candidate) => {
  try {
    const data = await addIceCandidate(url, candidate)
    console.log('Add ICE candidates')
    socket.emit('addIceCandidateResponse', data)
  } catch (error) {
    console.error('Error adding ICE candidate:', error)
  }
}

// Handle get a list of ICE candidates
export const handleGetIceCandidateRequest = async (socket, url) => {
  try {
    const data = await getIceCandidate(url)
    console.log('Get a list of ICE candidates')
    socket.emit('getIceCandidateResponse', data)
  } catch (error) {
    console.error('Error getting ICE candidates:', error)
  }
}
